package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kwd.rocketmq.RocketmqEvent;
import com.meirengu.channel.service.YiCaiDaoService;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.DateUtils;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.common.UserChannelEnum;
import com.meirengu.webview.dao.KwInterfaceConfigDao;
import com.meirengu.webview.model.KwInterfaceConfig;
import com.meirengu.webview.model.KwYcdFilter;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * KwYcdphFilter服务实现层
 *
 * @author Mao
 * @create Tue May 08 11:08:28 CST 2018
 */
@Service
public class KwYcdFilterServiceImpl extends BaseServiceImpl<KwYcdFilter> implements KwYcdFilterService {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private KwInterfaceConfigDao kwInterfaceConfigDao;

    @Autowired
    private YiCaiDaoService yiCaiDaoService;

    @Autowired
    private KwCyphPushService kwCyphPushService;

    @Autowired
    private KwYcdPushService kwYcdPushService;

    @Autowired
    private KwHnbPushService kwHnbPushService;


    Logger logger = LoggerFactory.getLogger(KwYcdFilterServiceImpl.class);


    /**
     * 发送中腾信接口
     * 过滤条件
     * 1公积金
     * 2年龄(23-55)
     * 3地址
     * 4去除企业主（false）
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendZTX(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        //校验是否有中腾信发送成功的记录
        Map<String, Object> ycdparams = new HashMap<>();
        ycdparams.put("mobile", user.getMobile());
        ycdparams.put("code", 1);
        Integer ycdCount = kwYcdPushService.getCount(ycdparams);
        //已有成功发送记录
        if (!NumberUtil.isNullOrZero(ycdCount)) {
            return sendFlag;
        }
        try {
            String ycdctcIol = redisClient.get("iol-ycdctc");
            if ("N".equals(ycdctcIol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();
                String city = userInfo.getScity();
                String idcard = userInfo.getIdCard();
                Integer housingType = userInfo.getHouse();
                Integer hasCar = userInfo.getCar();
                Integer housingFund = userInfo.getFund();
                Integer lifeInsurance = userInfo.getPolicy();
                Integer profession = userInfo.getOccupation();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer income = userInfo.getSalary();
                String ip = userInfo.getIp();
                Integer creditSituation = userInfo.getCredit();
                Integer paytype = userInfo.getSalaryMethod();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer weilidai = userInfo.getWxloan();
                Integer workDuration = userInfo.getWorkDuration();

                int age = 25;
                age = DateUtils.getAge(brithdayDate);
                int aSex = sex.intValue() + 1;
                String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");

                KwYcdFilter kwYcdFilter = new KwYcdFilter();
                kwYcdFilter.setUserId(id);
                kwYcdFilter.setMobile(mobile);
                kwYcdFilter.setChannelCode("ycdctc");
                kwYcdFilter.setChannelName("壹财道中腾信");

                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("ycdctc");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwYcdFilter.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwYcdFilter.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwYcdFilter.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitFund())) {
                        if (!kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "")) {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_FUND.getValue());
                            kwYcdFilter.setRefuseMsg("没有公积金：" + housingFund.intValue());
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getSocialSecurityValue().contains(socialSecurity.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "") ) {

                            int cardVal = 1;
                            if (creditSituation.intValue()==2) {
                                cardVal=1;
                            } else {
                                cardVal=2;
                            }
                            int ztxHouse = 1;
                            if (housingType.intValue() == 1) {
                                ztxHouse = 3;
                            } else if (housingType.intValue() == 2) {
                                ztxHouse = 1;
                            } else if (housingType.intValue() == 3) {
                                ztxHouse = 2;
                            }
                            int wageVal = 1;
                            if (income.intValue()>1 ) {
                                wageVal = income-1;
                            }
                            int loanAmount = (expectAmount.divide(new BigDecimal(10000))).intValue();
                            if (loanAmount < 1) {
                                loanAmount = 1;
                            }
                            int ztxCar = 1;
                            if (hasCar.intValue() == 1) {
                                ztxCar = 3;
                            } else if (hasCar.intValue() == 2) {
                                ztxCar = 1;
                            } else if (hasCar.intValue() == 3) {
                                ztxCar = 2;
                            }
                            int professionVal = 1;
                            //白领
                            if (profession.intValue()==0) {
                                professionVal = 1;
                                //私企业主
                            } else if (profession.intValue()==1) {
                                //私企业主都改为白领 modify by 2018-01-06
                                professionVal = 1;
                                //公务员
                            } else if (profession.intValue()==2) {
                                professionVal = 2;
                            }
                            Integer code = yiCaiDaoService.reg(ip, name, aSex+"", mobile, birthdayStr.substring(0,7),
                                    city, loanAmount+"",
                                    ztxHouse + "", ztxCar+"", cardVal+"", paytype+"",
                                    professionVal+"", wageVal+"",
                                    (socialSecurity+1)+"", (housingFund+1)+"", "", lifeInsurance+"");
                            kwYcdFilter.setSuited("Y");
                            kwYcdFilter.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            userInfoService.updateLimitNum(code, "ycdctc", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_FUND.getValue());
                            kwYcdFilter.setRefuseMsg("没有社保：" + housingFund.intValue() + " 没有车：" + hasCar.intValue());
                        }
                    }
                }

                insert(kwYcdFilter);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }


    /**
     * 发送壹财道普惠接口
     * 过滤条件
     * 1 年龄(21-55)
     * 2 房车寿 三其一
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendYCDPH(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        //校验是否有畅愿发送成功的记录
        Map<String, Object> cyphparams = new HashMap<>();
        cyphparams.put("mobile", user.getMobile());
        cyphparams.put("interfaceCode", "cyph");
        cyphparams.put("code", 1);
        Integer count = kwCyphPushService.getCount(cyphparams);
        //已有成功发送记录
        if (!NumberUtil.isNullOrZero(count)) {
            return sendFlag;
        }
        //校验是否有中腾信发送成功的记录
        Map<String, Object> ycdparams = new HashMap<>();
        ycdparams.put("mobile", user.getMobile());
        ycdparams.put("code", 1);
        Integer ycdCount = kwYcdPushService.getCount(ycdparams);
        //已有成功发送记录
        if (!NumberUtil.isNullOrZero(ycdCount)) {
            return sendFlag;
        }
        //校验是否有黑牛发送成功的记录
        Map<String, Object> hnbparams = new HashMap<>();
        hnbparams.put("mobile", user.getMobile());
        hnbparams.put("code", 1);
        Integer hnbCount = kwHnbPushService.getCount(hnbparams);
        //已有成功发送记录
        if (!NumberUtil.isNullOrZero(hnbCount)) {
            return sendFlag;
        }
        try {
            String ycdphIol = redisClient.get("iol-ycdph");
            if ("N".equals(ycdphIol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();
                String city = userInfo.getScity();
                Integer housingType = userInfo.getHouse();
                Integer hasCar = userInfo.getCar();
                Integer housingFund = userInfo.getFund();
                Integer lifeInsurance = userInfo.getPolicy();
                Integer profession = userInfo.getOccupation();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer income = userInfo.getSalary();
                String ip = userInfo.getIp();
                Integer creditSituation = userInfo.getCredit();
                Integer paytype = userInfo.getSalaryMethod();
                Integer socialSecurity = userInfo.getSocialSecurity();

                int age = 25;
                age = DateUtils.getAge(brithdayDate);
                int aSex = sex.intValue() + 1;
                String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");

                KwYcdFilter kwYcdFilter = new KwYcdFilter();
                kwYcdFilter.setUserId(id);
                kwYcdFilter.setMobile(mobile);
                kwYcdFilter.setChannelCode("ycdph");
                kwYcdFilter.setChannelName("壹财道普惠");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("ycdph");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwYcdFilter.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwYcdFilter.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwYcdFilter.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "")) {

                            int cardVal = 1;
                            if (creditSituation.intValue() == 2) {
                                cardVal = 1;
                            } else {
                                cardVal = 2;
                            }
                            int ztxHouse = 1;
                            if (housingType.intValue() == 1) {
                                ztxHouse = 3;
                            } else if (housingType.intValue() == 2) {
                                ztxHouse = 1;
                            } else if (housingType.intValue() == 3) {
                                ztxHouse = 2;
                            }

                            int ztxCar = 1;
                            if (hasCar.intValue() == 1) {
                                ztxCar = 3;
                            } else if (hasCar.intValue() == 2) {
                                ztxCar = 1;
                            } else if (hasCar.intValue() == 3) {
                                ztxCar = 2;
                            }

                            int wageVal = 1;
                            if (income.intValue() > 1) {
                                wageVal = income - 1;
                            }
                            int loanAmount = (expectAmount.divide(new BigDecimal(10000))).intValue();
                            if (loanAmount < 1) {
                                loanAmount = 1;
                            }
                            int professionVal = 1;
                            //白领
                            if (profession.intValue() == 0) {
                                professionVal = 1;
                                //私企业主
                            } else if (profession.intValue() == 1) {
                                //私企业主都改为白领 modify by 2018-01-06
                                professionVal = 1;
                                //公务员
                            } else if (profession.intValue() == 2) {
                                professionVal = 2;
                            }
                            Integer code = yiCaiDaoService.regPuhui(ip, name, aSex + "", mobile, birthdayStr.substring(0, 7),
                                    city, loanAmount + "",
                                    ztxHouse + "", ztxCar + "", cardVal + "", paytype + "",
                                    professionVal + "", wageVal + "",
                                    (socialSecurity + 1) + "", (housingFund + 1) + "", "", lifeInsurance + "");
                            kwYcdFilter.setSuited("Y");
                            kwYcdFilter.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            userInfoService.updateLimitNum(code, "ycdph", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            kwYcdFilter.setSuited("N");
                            kwYcdFilter.setCode(UserChannelEnum.FAIL_FUND.getValue());
                            kwYcdFilter.setRefuseMsg("没有社保：" + housingFund.intValue() + " 没有车：" + hasCar.intValue());
                        }
                    }
                }

                insert(kwYcdFilter);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }






}
